package cn.b.sky.mes.andon.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.b.sky.mes.andon.dao.AndonDao;
import cn.b.sky.mes.andon.dao.AndonGroupAssignDao;
import cn.b.sky.mes.andon.enums.AndonRunStatus;
import cn.b.sky.mes.andon.model.Andon;
import cn.b.sky.mes.andon.model.AndonGroupAssign;
import cn.b.sky.mes.andon.model.condition.AndonCondition;
import cn.b.sky.mes.andon.service.AndonService;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.utils.DatabaseUtils;
import cn.b.sky.i18n.utils.LocaleResourceBundle;
import cn.b.sky.user.SecurityContextUtil;

/**
 * 
 * <strong>Title : AndonServiceImpl.java<br></strong>
 * <strong>Package : cn.b.sky.mes.andon.service.impl<br></strong>
 * <strong>Description : </strong>按灯站点服务实现类<br> 
 * <strong>Create on : 2016年10月14日 下午1:15:37<br></strong>
 * <p>
 * @author dapeng.li<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人|修改日期|修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
@Service("andonService")
public class AndonServiceImpl implements AndonService {

  private static final Logger LOG = LoggerFactory.getLogger(AndonServiceImpl.class);

  @Autowired
  private AndonDao andonDao;

  @Autowired
  private AndonGroupAssignDao andonGroupAssignDao;

  private void checkAndonCondition(AndonCondition condition) {
    if (null == condition) {
      condition = new AndonCondition();
    }
    if (StringUtils.isEmpty(condition.getSiteCode())) {
      condition.setSiteCode(SecurityContextUtil.getCurrentUserName());
    }
  }

  @Override
  public List<Andon> getAndonListByCondition(AndonCondition condition) {
    checkAndonCondition(condition);
    return andonDao.getAndonListByCondition(condition);
  }

  @Override
  public int getAndonCountByCondition(AndonCondition condition) {
    checkAndonCondition(condition);
    return andonDao.getAndonCountByCondition(condition);
  }

  @Override
  public void insertAndon(Andon andon) {
    andonDao.insertAndon(andon);
  }

  @Override
  public void updateAndon(Andon andon) {
    andonDao.updateAndon(andon);
  }

  @Override
  public void batchUpdateAndons(List<Andon> andons) {
    for (Andon andon : andons) {
      andonDao.updateAndon(andon);
    }
  }

  @Override
  public Andon getAndonByCode(String siteCode, String workUnitCode, String andonCode) {
    return andonDao.getAndonByCode(siteCode, workUnitCode, andonCode);
  }

  @Override
  public BatchJobReport deleteAndon(String siteCode, String workUnitCode, String andonCode) {
    String cause = "";
    Boolean success = true;
    try {
      Andon andon = new Andon();
      andon.setSiteCode(siteCode);
      andon.setWorkUnitCode(workUnitCode);
      andon.setAndonCode(andonCode);
      andonGroupAssignDao.deleteGroupAssignsByAndon(andon);
      andonDao.deleteAndon(siteCode, workUnitCode, andonCode);
    } catch (Exception e) {
      LOG.error("{}", e);
      if (DatabaseUtils.isConstraintsError(e.getMessage())) {
        //外键删除已存在提示
        cause = LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
            SecurityContextUtil.getLanguageCode(), "dataBaseOperationPkFail.M")
            + LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
                SecurityContextUtil.getLanguageCode(), "notDelete.M");
      } else {
        cause = e.getMessage();
      }
      success = false;
    }
    return new BatchJobReport(andonCode, cause, success);
  }

  @Override
  public BatchJobReport doCopyAndon(Andon andon) {
    String cause = "";
    Boolean success = true;
    try {
      // 1、向目的作业单元插入ANDON数据
      andonDao.insertAndon(andon);
      // 2、如果选择的是ANDON组，保存组关系
      if (!StringUtils.isEmpty(andon.getAndonGroup())) {
        AndonGroupAssign assign = new AndonGroupAssign();
        assign.setSiteCode(andon.getSiteCode());
        assign.setAndonCode(andon.getAndonCode());
        assign.setWorkUnitCode(andon.getWorkUnitCode());
        assign.setAndonGroup(andon.getAndonGroup());
        andonGroupAssignDao.insertAndonGroupAssign(assign);
      }
    } catch (Exception e) {
      LOG.error("{}", e);
      if (DatabaseUtils.isExistingPKError(e.getMessage())) {
        // 主键已存在提示
        cause = LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
            SecurityContextUtil.getLanguageCode(), "dataIsExisting.M");
      } else {
        cause = e.getMessage();
      }
      cause += LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
          SecurityContextUtil.getLanguageCode(), "notCopy.M");
      success = false;
    }
    return new BatchJobReport(andon.getWorkUnitCode() + '-' + andon.getAndonCode(), cause, success);
  }

  @Override
  public BatchJobReport doMoveAndon(Andon andon) {
    String cause = "";
    String message = "";
    Boolean success = true;
    try {
      // 1、向目的作业单元插入ANDON数据
      andonDao.insertAndon(andon);
      // 2、如果选择的是ANDON组，保存组关系
      if (!StringUtils.isEmpty(andon.getAndonGroup())) {
        AndonGroupAssign assign = new AndonGroupAssign();
        assign.setSiteCode(andon.getSiteCode());
        assign.setAndonCode(andon.getAndonCode());
        assign.setWorkUnitCode(andon.getWorkUnitCode());
        assign.setAndonGroup(andon.getAndonGroup());
        andonGroupAssignDao.insertAndonGroupAssign(assign);
      }
      // 3、删除源ANDON组关系
      Andon originalAndon = new Andon();
      originalAndon.setSiteCode(andon.getSiteCode());
      originalAndon.setWorkUnitCode(andon.getOriginalWorkUnitCode());
      originalAndon.setAndonCode(andon.getAndonCode());
      andonGroupAssignDao.deleteGroupAssignsByAndon(originalAndon);
      // 4、删除源ANDON数据
      andonDao.deleteAndon(andon.getSiteCode(), andon.getOriginalWorkUnitCode(), andon.getAndonCode());
    } catch (Exception e) {
      LOG.error("{}", e);
      if (DatabaseUtils.isConstraintsError(e.getMessage())) {
        // 外键删除已存在提示
        cause = LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
            SecurityContextUtil.getLanguageCode(), "dataBaseOperationPkFail.M");
        message = andon.getOriginalWorkUnitCode();

      } else if (DatabaseUtils.isExistingPKError(e.getMessage())) {
        // 主键已经存在提示
        cause = LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
            SecurityContextUtil.getLanguageCode(), "dataIsExisting.M");
        message = andon.getWorkUnitCode();
      } else {
        cause = e.getMessage();
      }
      cause += LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
          SecurityContextUtil.getLanguageCode(), "notMove.M");
      success = false;
    }
    return new BatchJobReport(message + '-' + andon.getAndonCode(), cause, success);
  }

  @Override
  public Integer getRunningAndonCount(String siteCode, String workUnitCode, String andonType) {
    if (!StringUtils.isBlank(siteCode) && !StringUtils.isBlank(workUnitCode) && !StringUtils.isBlank(andonType)) {

      return andonDao.selectRunningAndonCountByType(siteCode, workUnitCode, AndonRunStatus.CLOSE.getValue(), andonType);
    }
    return null;
  }

  @Override
  public List<Andon> getAllAndonsByAndonType(String siteCode, String workUnitCode, String andonType) {
    return andonDao.selectAllAndonsByAndonType(siteCode, workUnitCode, andonType);
  }
}
